import React, {useEffect, useState} from 'react';
import {useNavigate, useParams} from 'react-router-dom';

import {useDispatch} from 'react-redux';
import {setToken, setUser} from '../redux/store';

import {Box, Container, Link, TextField, Typography} from '@mui/material';
import CircularProgress from '@mui/material/CircularProgress';
import LoadingButton from '@mui/lab/LoadingButton';
import LockResetIcon from '@mui/icons-material/LockReset';

import {getToken, getUserInfo} from "../api/common/login";

function LoginPage() {

    useEffect(() => {
        document.title = '登录';
    }, []);

    const [loginId, setLoginId] = useState(useParams().loginId || '');
    const [password, setPassword] = useState('');
    const [loading, setLoading] = useState(false);

    const navigate = useNavigate();
    const dispatch = useDispatch();

    const handleChange = (event) => {
        const {name, value} = event.target;
        if (name === 'loginId') {
            setLoginId(value);
        } else if (name === 'password') {
            setPassword(value);
        }
    };

    const handleSubmit = async (event) => {
        event.preventDefault();

        setLoading(true);
        const token = await getToken({loginId, password});
        if (token) {
            dispatch(setToken(token));
            const userInfo = await getUserInfo();
            if (userInfo) {
                dispatch(setUser(userInfo));

                setLoading(false);
                navigate('/index');
                return;
            }
        }
        setLoading(false);
    };

    return (
        <Container maxWidth="xs">
            <Box display="flex" flexDirection="column" justifyContent="center" minHeight="90vh">
                <form onSubmit={handleSubmit}>
                    <Box sx={{
                        width: '100%',
                        maxWidth: 480,
                        display: 'flex',
                        flexDirection: 'column',
                        justifyContent: 'flex-start',
                        gap: 2
                    }}>

                        <Typography variant="h5">登录</Typography>

                        <TextField
                            margin="normal" required fullWidth label="登录ID" name="loginId" autoFocus
                            value={loginId} onChange={handleChange} autoComplete='username'/>

                        <TextField margin="normal" required fullWidth label="密码" name="password" type="password"
                                   value={password} onChange={handleChange} autoComplete='current-password'/>

                        <LoadingButton
                            type="submit" disabled={loading} fullWidth
                            variant="contained" color="primary" size="large"
                            loadingIndicator={<CircularProgress color="inherit" size={24}/>}
                            loading={loading}>登录</LoadingButton>

                        <Link href="#" variant="body2" underline="none" display="flex" alignItems="center">
                            忘记密码?
                            <LockResetIcon/>
                        </Link>
                    </Box>
                </form>
            </Box>
        </Container>
    );
}

export default LoginPage;
